import { cloneDeep, intersection } from 'lodash-es'
import { useMainStore } from '@/store/useMainStore'
import type { RouteRecordRaw } from 'vue-router'
import is from '@/utils/is'

const filterAuthRoutes = (data: RouteRecordRaw[]) => {
  const mainStore = useMainStore()

  const dfs = (routes: RouteRecordRaw[]) => {
    return routes.filter((route) => {
      route.children = dfs(route.children || [])

      const whiteUserList = route.meta?.whiteUserList

      if (is.array(whiteUserList) && intersection(whiteUserList, [mainStore.userId]).length > 0) {
        return true
      } else if (is.array(route.meta?.auth)) {
        return intersection(mainStore.roles, route.meta?.auth ?? []).length > 0
      } else {
        return true
      }
    })
  }

  return dfs(data)
}

export function getAuthRoutes(routes: RouteRecordRaw) {
  routes = cloneDeep(routes)
  routes.children = filterAuthRoutes(routes.children!)
  // 只有在没有重定向配置时才设置为第一个子路由
  if (!routes.redirect) {
    routes.redirect = routes.children[0].path
  }

  return routes
}
